import 'package:ball_lion/module/expert/items/plan_list_item.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/home/live_logic.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/expert/items/league_hot_expert.dart';
import 'package:ball_lion/module/live/items/live_list_view.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:ball_lion/base/base_builder.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/widgets/base/wqs_carousel_view.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/base/wqs_indicator.dart';

class LiveListPage extends StatefulWidget {
  const LiveListPage({super.key});

  @override
  State<LiveListPage> createState() => _LiveListPageState();
}

class _LiveListPageState extends State<LiveListPage>
    with AutomaticKeepAliveClientMixin {
  final LiveLogic logic = Get.put(LiveLogic());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return VisibilityDetector(
      key: const Key("home_live"),
      onVisibilityChanged: (VisibilityInfo info) {
        if (!info.visibleBounds.isEmpty) logic.getRefresh();
      },
      child: RefreshBuilder<LiveLogic>(
        needLoad: true,
        scrollController: logic.refreshScroll,
        header: Styles.refreshHeader(
            position: IndicatorPosition.locator, clamping: true),
        footer: Styles.refreshFooter(position: IndicatorPosition.locator),
        builder:
            (LiveLogic logic, BuildContext context, ScrollPhysics physics) {
          return ExtendedNestedScrollView(
              controller: logic.refreshScroll,
              physics: physics,
              onlyOneScrollInBody: true,
              pinnedHeaderSliverHeightBuilder: () => 36,
              headerSliverBuilder:
                  (BuildContext context, bool innerBoxIsScrolled) => [
                        const HeaderLocator.sliver(clearExtent: false),
                        if (logic.carousel.hasValue)
                          SliverToBoxAdapter(
                            child: QsCarouselView(
                              carousels: logic.carousel,
                              aspectRatio: 359 / 120,
                              radius: 8,
                              padding: 8,
                              needDot: logic.carousel.length > 1,
                              tapType: "live_banner",
                            ).marginOnly(top: 8),
                          ),
                        SliverToBoxAdapter(
                          child: Styles.tabbar(
                              controller: logic.tabController,
                              tabs: logic.tabs
                                  .map<Widget>((e) => QsText(e))
                                  .toList(),
                              labelColor: Colours.text,
                              unselectedLabelColor: Colours.grey99,
                              scrollable: true,
                              labelPadding: const EdgeInsets.only(right: 16),
                              indicator: const QsIndicator.none(),
                              onTap: (value) {
                                logic.currentIndex = value;
                                Utils.onEvent("zbfl",
                                    params: {"zbfl": "tab_$value"});
                              }).paddingOnly(top: 12, left: 8, bottom: 4),
                        )
                      ],
              body: TabBarView(
                  physics: const NeverScrollableScrollPhysics(),
                  controller: logic.tabController,
                  children: List.generate(
                      logic.tabs.length,
                      (index) => LoadingWidget<bool>(
                            physics: physics,
                            needScroll: true,
                            isLoading: logic.lives[index]?.length == null &&
                                logic.pages[index]?.length == null,
                            data: logic.lives[index]?.length == 0 &&
                                logic.pages[index]?.length == 0,
                            child: () => CustomScrollView(
                              physics: physics,
                              slivers: [
                                if (logic.lives[index].hasValue)
                                  LiveListView.sliver(
                                      list: logic.lives[index]
                                          ?.where(
                                              (element) => element.status != 2)
                                          .toList()),
                                LiveListView.sliver(
                                    title: "精彩回放",
                                    maxShow: 2,
                                    list: logic.lives[index]
                                        ?.where(
                                            (element) => element.status == 2)
                                        .toList()),
                                SliverToBoxAdapter(
                                  child: HotExpertBoard(
                                    controller: logic.boardController[index],
                                    eventType: 'live_hot_host',
                                  ).paddingOnly(top: 8, left: 8, right: 8),
                                ),
                                if (logic.pages[index]?.hasValue ?? false) ...[
                                  SliverToBoxAdapter(
                                      child: Container(
                                    padding: const EdgeInsets.all(12),
                                    child: const QsText("专家方案",
                                        fontSize: 16,
                                        fontWeight: FontWeight.w500),
                                  )),
                                  SliverList(
                                      delegate: SliverChildBuilderDelegate(
                                          childCount:
                                              logic.pages[index]!.length,
                                          (context, i) => Block(
                                              cardStyle: const CardStyle(
                                                  padding: EdgeInsets.symmetric(
                                                      horizontal: 12),
                                                  margin: EdgeInsets.fromLTRB(
                                                      8, 0, 8, 8)),
                                              child: PlanListItem(
                                                planList:
                                                    logic.pages[index]![i],
                                                eventType: 'live_plan_view',
                                              )))),
                                  const FooterLocator.sliver(),
                                ] else
                                  SliverToBoxAdapter(
                                      child: Container(height: 50))
                              ],
                            ),
                          ))));
        },
      ),
    );
  }

  Widget showMore(int index) {
    return Block(
        cardStyle: const CardStyle(
          height: 40,
          margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
        ),
        onTap: () {
          logic.hasMore[index] = !logic.hasMore[index]!;
          update();
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            QsText(logic.hasMore[index] == false ? "点击收起" : "点击展开",
                fontSize: 12, color: Colours.grey99),
            Container(width: 2),
            Image.asset(
                width: 16,
                Utils.getImgPath(logic.hasMore[index] == false
                    ? "arrow_up.png"
                    : "arrow_down.png"))
          ],
        ));
  }

  @override
  bool get wantKeepAlive => true;
}
